/*
 加载模块
 */
var _ = require('underscore');
var config = require('../config');
_.mixin(require('../underscore.mixin'));
var fs = require('fs');
/*
 全局变量
 */
var _grunt;
var _global = config.getGlobal();
/*
 一些路径
 */
var path = {
    templates: './Gruntfile/' + _global.groupName + '/templates',
    apps: './apps/' + _global.groupName,
    build: './build/' + _global.groupName,
    debug: './debug/' + _global.groupName,
    assets: '../app/Tpl/' + _global.groupName + '/public'
};
/*
 模板文件
 */
var JS_ENTRY_FILE = path.templates + '/group.html';
var JS_DEBUG_FILE = path.templates + '/debug.html';
var JS_LOAD_FILE = path.templates + '/js.html';

module.exports = function(grunt) {
    var _this = this;
    grunt.registerTask('build', function() {
        grunt.file.delete(path.build);
        grunt.file.defaultEncoding = 'utf8';
        grunt.task.run('requirejs');
        //grunt.task.run('less');
    });
    grunt.registerTask('debug', function() {
        grunt.file.delete(path.debug);
        //生成分组入口文件
        _.each(_global.groupRules, function(val, key) {
            var data = fs.readFileSync(JS_ENTRY_FILE, 'utf8');
            var file = _.sprintf("%s/%s.js", path.debug, _global.entryPrefix + key);
            grunt.file.write(file, _.template(data, {
                modules: val,
                name: key,
                entryPrefix: _global.entryPrefix
            }));
            console.log("生成:" + file);
        });
        //生成requirejs配置文件（用于调试）
        var data = fs.readFileSync(JS_DEBUG_FILE, 'utf8');
        var content = _.template(data, {
            config: JSON.stringify(config.getRequireConfig('__STATIC_URL__/')),
            now: _.date('Y-m-d H:i:s')
        });
        content = _.str_replace('"__STATIC_URL__/', '_global.static_url+"', content);
        var file = path.debug + '/requireConfig.js';
        grunt.file.write(file, content);
        console.log("生成:" + file);
        //生成js加载文件
        data = fs.readFileSync(JS_LOAD_FILE, 'utf8');
        content = _.template(data, {
            rules: _global.groupRules,
            prefix: _global.entryPrefix
        });
        file = '../app/Tpl/' + _global.groupName + '/public/js.html';
        grunt.file.write(file, content);
        console.log("生成:" + file);
    });
    this.getInitConfig = function() {
        var files = {};
        _.each(grunt.file.readJSON(path.assets + '/css/config.json').cssmin, function(val, key) {
            files[path.assets + '/cssmin/' + key] = [];
            _.each(val, function(v, k) {
                files[path.assets + '/cssmin/' + key].push(path.assets + '/css/' + v);
            });
        });
        return {
            cssmin: {
                target: {
                    files: files
                }
            }
        };
    };

    this.generateRequirejsConfig = function() {
        var _this = this,
            dirs = _.getDirName(path.apps),
            result = {},
            wrapEnd;

        _.each(_global.groupRules, function(val, key) {
            var path_debug = path.apps;
            var path_build = path.build + '/' + _global.entryPrefix + key;
            var name = '../../debug/' + _global.groupName + '/' + _global.entryPrefix + key;
            var wrapEnd = 'var req = require.config({\
            baseUrl:_global.static_url+"%s"});\
            req(["' + name + '"], function (App) {\
                new App();\
            });';
            result[key] = {
                options: _.extend({}, _.extend({
                    //TRACE: 0,INFO: 1,WARN: 2,ERROR: 3,SILENT: 4,
                    logLevel: 3,
                    config: {
                        text: {
                            useXhr: function(url, protocol, hostname, port) {
                                return true;
                            }
                        }
                    },
                    optimize: "uglify2",
                    uglify2: {
                        //mangle: true
                    },
                    stubModules: ['text'],
                    inlineText: true,
                    findNestedDependencies: true,
                    optimizeAllPluginResources: true,
                    preserveLicenseComments: false,
                    name: name
                }, config.getRequireConfig('../../')), {
                    wrap: {
                        startFile: [
                            "vendor/build.js",
                            "vendor/require.js",
                            "vendor/underscore.js",
                            "vendor/underscore.mixin.js"
                        ],
                        end: _.sprintf(wrapEnd, path_debug, path_build)
                    },
                    baseUrl: 'apps/' + _global.groupName,
                    out: path_build + '.js'
                })
            };
        });
        return result;
    };

    this.generateLessConfig = function() {
        return {};
    };

    this.generateWatchConfig = function() {
        return {};
    }
};